# -*- coding: utf-8 -*-

"""
@Author: Rwing
@File: my_form.py
@Time: 2021/12/5 12:32
"""
from django import forms
from django.core.exceptions import ValidationError

from App import models as app_models


class UserRegisterForm(forms.Form):
    """
    用户注册表单
    """
    username = forms.CharField(
        min_length=6,
        max_length=32,
        label="用户名",
        required=True,
        error_messages={
            "min_length": "不能少于6个字符",
            "max_length": "不能大于32个字符",
            "required": "用户不能为空",
        }
    )
    password = forms.CharField(
        min_length=6,
        max_length=16,
        label="密码",
        required=True,
        error_messages={
            "min_length": "不能少于6个字符",
            "max_length": "不能大于16个字符",
            "required": "密码不能为空",
        }
    )
    confirm_password = forms.CharField(
        min_length=6,
        max_length=16,
        label="密码",
        required=True,
        error_messages={
            "min_length": "不能少于6个字符",
            "max_length": "不能大于16个字符",
            "required": "密码不能为空",
        }
    )
    email = forms.CharField(
        label="邮箱",
        required=True,
        error_messages={
            "required": "邮箱不能为空",
        }
    )
    icon = forms.ImageField(
        label="头像",
        required=True,
        error_messages={
            "required": "头像不能为空",
        }
    )

    def check_username(self):
        """
        用户注册检测用户名规则和检测用户名是否存在
        :return:
        """
        print("检测用户名")
        username = self.changed_data.get("username")
        if username.isdigit() and username.isalpha():
            print("纯数字/纯字母")
            raise ValidationError("用户名不能是纯数字/纯字母！")
        elif app_models.AXFUsers.objects.filter(u_username=username):
            print("已存在")
            raise ValidationError("用户名已存在！")
        else:
            return username

    def check_password_consistency(self):
        password = str(self.changed_data.get("password"))
        confirm_password = self.changed_data.get("confirm_password")
        if password.isdigit() and password.isalpha():
            raise ValidationError("密码必须包含数字、字母")
        elif password != confirm_password:
            raise ValidationError("两次输入的密码不一致")
        else:
            return self.changed_data


class UserLoginForm(forms.Form):
    username = forms.CharField(
        min_length=6,
        max_length=32,
        label="用户名/邮箱",
        required=True,
        error_messages={
            "min_length": "不能少于6个字符",
            "max_length": "不能大于32个字符",
            "required": "用户名/邮箱不能为空",
        }
    )
    password = forms.CharField(
        min_length=6,
        max_length=16,
        label="密码",
        required=True,
        error_messages={
            "min_length": "不能少于6个字符",
            "max_length": "不能大于16个字符",
            "required": "密码不能为空",
        }
    )
